package com.allwees.bs.c.module.payment.controller;

import cn.hutool.crypto.SecureUtil;
import com.allwees.bs.c.module.order.dto.OrderItemDTO;
import com.allwees.bs.c.module.order.entity.OrderEntity;
import com.allwees.bs.c.module.order.service.IOrderItemService;
import com.allwees.bs.c.module.payment.service.OceanpayService;
import com.allwees.bs.core.model.user.context.CurrentUser;
import com.allwees.bs.core.modelbase.vo.R;
import com.allwees.core.common.util.StringUtil;
import com.allwees.core.common.util.http.RequestContext;
import com.allwees.support.payment.oceanpay.config.OceanpayProperties;
import com.allwees.support.payment.oceanpay.dto.PayParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Daniel
 * @version 1.0.0
 * @since 2020/12/6 13:41
 */
@Slf4j
@RestController
public class OceanpayController {

    @Autowired
    private OceanpayProperties properties;

    @Autowired
    private OceanpayService oceanpayService;

    @Autowired
    private IOrderItemService orderItemService;
    /**
     * 创建oceanpay支付
     * @param orderUuid
     * @return
     */
    @PostMapping("/api/v1/payment/oceanpay")
    public R oceanpayParams(@RequestParam("orderUuid") String orderUuid) {
        return R.ok(assembleOeanpayParams(orderUuid));
    }

    private PayParam assembleOeanpayParams(String orderUuid){
        OrderEntity order = oceanpayService.getOrder(orderUuid);
        PayParam param = new PayParam();
        param.setAccount(properties.getAccount());
        param.setTerminal(properties.getTerminal());
        if (RequestContext.getPlatform().isApp()) {
            param.setPages("1");
        }
        //ongo backurl?
        param.setBackUrl(properties.getBackUrl());
        param.setNoticeUrl(properties.getNoticeUrl());
        param.setOrder_number(orderUuid);

        //master:USD
        //master-ae:AED 迪拉姆
        //master-sa:SAR 沙亚币
        param.setOrder_currency(order.getCurrency());
        param.setOrder_amount(order.getAmt().toPlainString());

        List<OrderItemDTO> items = orderItemService.findOrderItems(orderUuid);
        String skus = items.stream().map(OrderItemDTO::getSkuUuid).collect(Collectors.joining(","));
        param.setProductSku(skus);
        int num = items.stream().map(OrderItemDTO::getQuantity).mapToInt(Integer::intValue).sum();
        param.setProductNum(String.valueOf(num));
        param.setProductName("N/A");

        //HtmlEscapers.htmlEscaper().escape()
        String firstName = StringUtil.strip(order.getShippingAddressFirstName());
        String lastName = StringUtil.strip(order.getShippingAddressLastName());
        String phone = order.getShippingAddressPhone();
        param.setBilling_firstName(firstName);
        param.setBilling_lastName(lastName);
        param.setBilling_email(CurrentUser.getUser().getUsername());
        param.setBilling_phone(phone);

        param.setBilling_country("N/A");
        param.setBilling_state("N/A");
        param.setBilling_city("N/A");
        param.setBilling_address("N/A");
        param.setBilling_zip("N/A");

        param.setShip_firstName(firstName);
        param.setShip_lastName(lastName);
        param.setShip_phone(phone);

        String country = StringUtil.firstNonBlank(StringUtil.strip(order.getShippingAddressCountry()),"N/A");
        param.setShip_country(country);
        String address = StringUtil.join(StringUtil.strip(order.getShippingAddressFirstName()), StringUtil.strip(order.getShippingAddressLine2()));
        address = StringUtil.firstNonBlank(address,"N/A");
        param.setShip_addr(address);
        String city = StringUtil.firstNonBlank(StringUtil.strip(order.getShippingAddressCity()),"N/A");
        param.setShip_city(city);

        String zipCode = StringUtil.firstNonBlank(StringUtil.strip(order.getShippingAddressZipCode()),"N/A");
        param.setShip_zip(zipCode);

        String province = StringUtil.firstNonBlank(StringUtil.strip(order.getShippingAddressProvince()),"N/A");
        param.setShip_state(province);

        setSignValue(param);
        return param;
    }

    /**
     * account+
     * terminal+
     * backUrl+
     * order_number+
     * order_currency+
     * order_amount+
     * billing_firstName+
     * billing_lastName+
     * billing_email+
     * secureCode
     * @param payParam
     * @return
     */
    private void setSignValue(PayParam payParam){
        String signStr =
                StringUtil.join(
                        payParam.getAccount(),
                        payParam.getTerminal(),
                        payParam.getBackUrl(),
                        payParam.getOrder_number(),
                        payParam.getOrder_currency(),
                        payParam.getOrder_amount(),
                        payParam.getBilling_firstName(),
                        payParam.getBilling_lastName(),
                        payParam.getBilling_email(),
                        properties.getSecureCode()
                );
        payParam.setSignValue(SecureUtil.sha256(signStr));
    }
}
